package com.km.wskj.itmonitor.pager.monitor.server;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.SpannableString;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.fingdo.statelayout.StateLayout;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.model.AlarmStatus;
import com.km.wskj.itmonitor.model.AlarmType;
import com.km.wskj.itmonitor.model.TypeStatistics;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.zxl.zxlapplibrary.util.LogUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @author by Xianling.Zhou on 2017/3/1.
 */
//服务器统计
public class ServerStatisticsActivity extends LActivity implements StateLayout.OnViewRefreshListener {
    private static final String TAG = "ServerStatisticsActivit";

    //ui
    @BindView(R.id.tool_bar_title)
    TextView mTitle;
    @BindView(R.id.tool_bar_back)
    ImageView mBack;
    @BindView(R.id.type_pieChart)
    PieChart typePieChart;
    @BindView(R.id.alarm_type_pieChart)
    PieChart alarmTypePieChart;
    @BindView(R.id.alarm_state_pieChart)
    PieChart alarmStatePieChart;
    @BindView(R.id.state_layout)
    StateLayout stateLayout;

    //data
    private ArrayList<PieEntry> entries;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_server_statistics);
        ButterKnife.bind(this);

        mBack.setVisibility(View.VISIBLE);
        mTitle.setText("服务器统计");
        stateLayout.setRefreshListener(this);

        initData();

    }

    private void initData() {
        stateLayout.showLoadingView();
        //类型统计
        pdc.serverTypeStatis(HTTP_TASK_TAG, new ZxlGenericsCallback<List<TypeStatistics>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                stateLayout.showErrorView();
            }

            @Override
            public void onResponse(List<TypeStatistics> typeStatistics, int i) {
                entries = new ArrayList<>();
                int total = 0;

                for (TypeStatistics tys : typeStatistics
                        ) {
                    //添加数据
                    entries.add(new PieEntry(Float.parseFloat(tys.num + ""), tys.typeName + ""));
                    total += tys.num;
                }

                initChart(typePieChart, entries, "服务器分布图", "服务器总数\n" + total);

            }
        });

        //报警类型统计
        pdc.serverAlarmTypeStatis(HTTP_TASK_TAG, new ZxlGenericsCallback<List<AlarmType>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                stateLayout.showErrorView();
            }

            @Override
            public void onResponse(List<AlarmType> alarmTypes, int i) {
                entries = new ArrayList<>();
                int total = 0;

                for (AlarmType at : alarmTypes
                        ) {
                    //添加数据
                    entries.add(new PieEntry(Float.parseFloat(at.num + ""), at.level2Name + ""));
                    total += at.num;
                }
                initChart(alarmTypePieChart, entries, "报警分布图", "报警分布\n" + total);
            }
        });

        //报警状态统计
        pdc.serverAlarmStatus(HTTP_TASK_TAG, new ZxlGenericsCallback<AlarmStatus>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                stateLayout.showErrorView();
            }

            @Override
            public void onResponse(AlarmStatus alarmStatus, int i) {
                entries = new ArrayList<>();
                int total = 0;
                //添加数据
                entries.add(new PieEntry(Float.parseFloat(alarmStatus.num1 + ""), "未处理"));
                entries.add(new PieEntry(Float.parseFloat(alarmStatus.num2 + ""), "已处理"));
                total = alarmStatus.num1 + alarmStatus.num2;

                initChart(alarmStatePieChart, entries, "处理分布", "报警总数\n" + total);

                stateLayout.showContentView();
            }
        });

    }

    /**
     * @param mPieChart 控件
     * @param entries   数据
     * @param str       比例图名称
     * @param centerStr 饼图中心标题
     */
    private void initChart(PieChart mPieChart, ArrayList<PieEntry> entries, String str, String centerStr) {
        //设置饼图是否使用百分比
        mPieChart.setUsePercentValues(true);
        //设置饼图右下角的文字描述
      /*  Description d = new Description();
        d.setText(str);
        mPieChart.setDescription(d);*/
        mPieChart.getDescription().setEnabled(false);
//        mPieChart.setExtraOffsets(5, 10, 5, 5);

//        mPieChart.setDragDecelerationFrictionCoef(0.95f);
        //设置中间文件
        mPieChart.setCenterText(generateCenterSpannableText(centerStr));

        mPieChart.setDrawHoleEnabled(true);
        mPieChart.setHoleColor(Color.WHITE);

        mPieChart.setTransparentCircleColor(Color.WHITE);
        mPieChart.setTransparentCircleAlpha(110);

        mPieChart.setHoleRadius(58f); //设置中间圆盘的半径,值为所占饼图的百分比
        mPieChart.setTransparentCircleRadius(61f);//设置中间透明圈的半径,值为所占饼图的百分比
        mPieChart.setDrawCenterText(true);


        mPieChart.setRotationAngle(0);
        // 触摸旋转
        mPieChart.setRotationEnabled(true);
        mPieChart.setHighlightPerTapEnabled(true);

        //变化监听
//        mPieChart.setOnChartValueSelectedListener(this);

        //设置数据
        setData(entries, mPieChart, str);

        mPieChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);

        //设置比例图
        Legend l = mPieChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        l.setXEntrySpace(2f);//设置距离饼图的距离，防止与饼图重合
        l.setYEntrySpace(2f);
        l.setYOffset(0f);
        l.setForm(Legend.LegendForm.SQUARE);//设置比例块形状，默认为方块
        //        l.setEnabled(false);//设置禁用比例块
        //设置比例块换行...
        l.setWordWrapEnabled(true);


        // 输入标签样式
        mPieChart.setEntryLabelColor(Color.WHITE);
        mPieChart.setEntryLabelTextSize(12f);
    }

    @OnClick(R.id.tool_bar_back)
    public void back() {
        finish();
    }


    //设置中间文字
    private SpannableString generateCenterSpannableText(String str) {
        //原文：MPAndroidChart\ndeveloped by Philipp Jahoda
        SpannableString s = new SpannableString(str);
        //s.setSpan(new RelativeSizeSpan(1.7f), 0, 14, 0);
        //s.setSpan(new StyleSpan(Typeface.NORMAL), 14, s.length() - 15, 0);
        // s.setSpan(new ForegroundColorSpan(Color.GRAY), 14, s.length() - 15, 0);
        //s.setSpan(new RelativeSizeSpan(.8f), 14, s.length() - 15, 0);
        // s.setSpan(new StyleSpan(Typeface.ITALIC), s.length() - 14, s.length(), 0);
        // s.setSpan(new ForegroundColorSpan(ColorTemplate.getHoloBlue()), s.length() - 14, s.length(), 0);
        return s;
    }

    //设置数据
    private void setData(ArrayList<PieEntry> entries, PieChart mPieChart, String str) {

        PieDataSet dataSet = new PieDataSet(entries, str);
        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(5f);

        //数据和颜色
        ArrayList<Integer> colors = new ArrayList<>();

        int[] MyColors = {
                Color.rgb(0, 238, 118), Color.rgb(100, 149, 237),
                Color.rgb(0, 191, 255), Color.rgb(255, 165, 0)
        };

        for (int c : MyColors)
            colors.add(c);


        dataSet.setColors(colors);
        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.WHITE);
        mPieChart.setData(data);
        mPieChart.highlightValues(null);

        //刷新
        mPieChart.invalidate();
    }

    @Override
    public void refreshClick() {
        initData();
    }

    @Override
    public void loginClick() {

    }
}
